<?php


namespace jrsy\help\wxmini;



use jrsy\help\http\Http;

class BaseWechat
{

    //微信登录凭证换取openid接口
    const MINI_JSCODE2SESSION_URL = "/sns/jscode2session?";

    const API_BASE_URL_PREFIX = 'https://api.weixin.qq.com';

    public $appid ='';

    public $appsecret = '';

    public $config = [];


    /**
     * 构造方法
     * @param array $config
     */
    public function __construct($config = array()){
        $this->appid = isset($config['appid']) ? $config['appid'] : '';
        $this->appsecret = isset($config['appsecret']) ? $config['appsecret'] : '';
        $this->config = $config;
    }


    //获取openid
    public function code2Session($code){

        $result = Http::httpGet(self::API_BASE_URL_PREFIX . self::MINI_JSCODE2SESSION_URL . "appid={$this->appid}&secret={$this->appsecret}&js_code={$code}&grant_type=authorization_code");

        if(false === $result){
            return false;
        }

        $result = json_decode($result,true);

        if(array_key_exists("errcode",$result)){
            return false;
        }

        return $result;
    }


    /**
     * @dec 获取手机号
     * 小程序检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $sessionKey
     * @return int 成功0，失败返回对应的错误码
     */

    public function decryptData( $encryptedData,$iv,$sessionKey)
    {
        if (strlen($sessionKey) != 24) {
            return  false;
        }

        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            return  false;
        }

        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result = openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj= json_decode( $result );

        if( $dataObj  == NULL ){
            return  false;
        }

        if( $dataObj->watermark->appid != $this->appid ){
            return  false;
        }

        return $result;

    }



}
